package com.huaboot.framework.security.filter;


import cn.hutool.core.util.StrUtil;
import com.huaboot.commont.exception.BusinessException;
import com.huaboot.commont.exception.ErrorCode;
import com.huaboot.framework.redis.config.RedisCache;
import com.huaboot.framework.security.user.LoginUser;
import com.huaboot.framework.security.utils.JwtUtil;
import com.huaboot.framework.security.utils.SecurityUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 认证过滤器
 */
@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {


    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //获取token内容
        String accessToken = SecurityUtil.getAccessToken(request);
        // accessToken为空，表示未登录,过滤结束
        if (StringUtils.isBlank(accessToken)) {
            chain.doFilter(request, response);
            return;
        }

        //解析token
        String userId = "";
        try {
            Claims claims = JwtUtil.parseJWT(accessToken);
            userId = claims.getSubject();
        } catch (Exception e) {
            chain.doFilter(request, response);
            return;
            //throw new BusinessException(ErrorCode.TOKEN_ERROR);
        }

        //用userid--key去redis过去用户信息
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 用户存在
        Authentication authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        // 新建 SecurityContext
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);
        chain.doFilter(request, response);
    }


}
